const { Op } = require("sequelize");
const NoticesModels = require('../models/notices');

interface notice {
    content: string,
    picture: string
}

class NoticeService {
    // 获取公告列表
    public async getNotices() {
        const res: any = await NoticesModels.findAndCountAll()
        return res ? res : null
    }
    // 分页获取公告列表
    public async getNoticesByPageInfo(pageNum: number, pageSize: number) {
        const offset = (pageNum - 1) * pageSize
        const { count, rows } = await NoticesModels.findAndCountAll({
            offset: offset,
            limit: pageSize * 1
        })
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows
        }
    }
    // 根据关键词搜索公告列表
    public async getNoticesByKeyword(keyword: string) {
         // 不分页直接获取
         const { count, rows } = await NoticesModels.findAndCountAll({
            where: {
                content: {
                    [Op.like]: `%${keyword}%`,
                }
            }
        })
        return {
            total: count,
            list: rows
        }
    }
    // 分页获取-根据关键词搜索公告列表
    public async getByKeywordandPageInfo(pageNum: number, pageSize: number, keyword: string) {
        const offset = (pageNum - 1) * pageSize
        const { count, rows } = await NoticesModels.findAndCountAll({
            where: {
                content: {
                    [Op.like]: `%${keyword}%`,
                }
            },
            offset: offset,
            limit: pageSize * 1
        })
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows
        }
    }
    // 根据id获取公告
    public async getInfoById(id: number) {
        const res = await NoticesModels.findOne({
            where: {
                id
            }
        })
        return res? res.dataValues : null
    }
    // 添加公告
    public async createNotice(params: notice) {
        const res: any = await NoticesModels.create(params)
        return res ? res.dataValues : null;
    }
    // 更新公告
    public async update(id: number, params: notice) {
        const whereOpt = { id }
        const res = await NoticesModels.update(params, { where: whereOpt })
        return res[0] > 0
    }
    // 删除公告
    public async deleteNot(id: number) {
        const res: any = await NoticesModels.destroy({
            where: { id }
        })
        return res > 0
    }
}

module.exports = new NoticeService()
// 解决同目录下多个ts文件都引入Op,会报错的问题
export {}